#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from cors_middleware import CorsResource
import json
from utility import tools

class UserResource(CorsResource):
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state  # 共享游戏状态

    def render_GET(self, request):
        self._set_cors_headers(request)
        user_id = request.args.get(b'user_id', b'')[0].decode()
        action = request.args.get(b'action', b'')[0].decode()

        # 确保玩家存在
        if user_id not in self.game_state.users:
            # 尝试从数据库加载
            user_data = self.game_state.load_user_from_db(user_id)
            if not user_data:
                # 数据库中也不存在，创建新玩家
                self.game_state.users[user_id] = {'x': 0, 'y': 0, 'inventory': []}
        else:
            # 玩家在内存中存在，确保数据库中也有
            self.game_state.save_user_to_db(user_id)

        # 玩家移动逻辑
        if action == 'move_up':
            self.game_state.users[user_id]['y'] += 10
        elif action == 'move_down':
            self.game_state.users[user_id]['y'] -= 10
        elif action == 'move_left':
            self.game_state.users[user_id]['x'] -= 10
        elif action == 'move_right':
            self.game_state.users[user_id]['x'] += 10

        # 保存更新后的玩家数据
        self.game_state.save_user_to_db(user_id)

        response = {
            'code': 0,
            'data': {
                'user_id': user_id,
                'position': self.game_state.users[user_id]
            }
        }
        response = tools.dict_snake_case_to_camel(response)
        request.setHeader(b'Content-Type', b'application/json')
        return json.dumps(response).encode()
